package cn.zch.cmbchina.util.cmb;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class SignCmbUtil {
  // 排序
  public static String sortMap(Map<Object, Object> paramMap) {
    StringBuilder sort = new StringBuilder();
    MapUtil signMap = new MapUtil();
    if (paramMap != null) {
      String key;
      for (Object item : paramMap.keySet()) {
        key = (String) item;
        String value = ((paramMap.get(key) != null) && (!("".equals(paramMap.get(key).toString())))) ? paramMap.get(key).toString() : "";
        signMap.put(key, value);
      }
      signMap.sort();
      for (Object o : signMap.keySet()) {
        key = (String) o;
        sort.append(key).append("=").append(signMap.get(key).toString()).append("&");
      }
      if (!"".equals(sort.toString())) {
        sort = new StringBuilder(sort.substring(0, sort.length() - 1));
      }
    }
    return sort.toString();
  }
  // 排序
  public static String sortJson(JSONObject jsonMap) {
    Map<String, String> paramMap = new HashMap<>();
    // 将json字符串转换成jsonObject
    JSONObject jsonObject = JSONObject.fromObject(jsonMap);
    Iterator<?> ite = jsonObject.keys();
    // 遍历jsonObject数据,添加到Map对象
    while (ite.hasNext()) {
      String key = ite.next().toString();
      String value = jsonObject.get(key).toString();
      paramMap.put(key, value);
    }
    StringBuilder sort = new StringBuilder();
    MapUtil signMap = new MapUtil();
    String key1;
    for (String s : paramMap.keySet()) {
      key1 = s;
      String value = ((paramMap.get(key1) != null) && (!("".equals(paramMap.get(key1))))) ? paramMap.get(key1) : "";
      signMap.put(key1, value);
    }
    signMap.sort();
    for (Object o : signMap.keySet()) {
      key1 = (String) o;
      sort.append(key1).append("=").append(signMap.get(key1).toString()).append("&");
    }
    if (!"".equals(sort.toString())) {
      sort = new StringBuilder(sort.substring(0, sort.length() - 1));
    }
    return sort.toString();
  }
}
